﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace CustomerService
{
    public partial class tabShipTo : System.Web.UI.UserControl
    {
        private SalesManagerEntities _context;
        private static tblOrderHeader _emptyOrder = new tblOrderHeader();
        protected tblOrderHeader _orderHeader = _emptyOrder;
        private static tblPerson _emptyPerson = new tblPerson();
        protected tblPerson _person = _emptyPerson;
        private static tblAddress _emptyAddress = new tblAddress();
        protected tblAddress _address = _emptyAddress;
        protected bool _enabled = true;

        protected void Page_Load(object sender, EventArgs e)
        {
            SetEnabled();

            if (IsPostBack)
            {
                if (!chkSameAsBilling.Checked)
                {
                    if (((_person.FirstName == null) ? string.Empty : _person.FirstName.Trim()) != txtFirstName.Text.Trim() ||
                        ((_person.LastName == null) ? string.Empty : _person.LastName.Trim()) != txtLastName.Text.Trim())
                        _person.Name = txtFirstName.Text.Trim() + " " + txtLastName.Text.Trim();

                    _person.FirstName = txtFirstName.Text;
                    _person.LastName = txtLastName.Text;

                    if ((_address.Address1 ?? string.Empty).Trim() != txtAddress1.Text.Trim())
                        _address.Address1 = txtAddress1.Text;
                    if ((_address.Address2 ?? string.Empty).Trim() != txtAddress2.Text.Trim())
                        _address.Address2 = txtAddress2.Text;
                    if ((_address.Address3 ?? string.Empty).Trim() != txtInternationalAddress2.Text.Trim())
                        _address.Address2 = txtInternationalAddress2.Text;
                    if ((_address.Address3 ?? string.Empty).Trim() != txtInternationalAddress3.Text.Trim())
                        _address.Address3 = txtInternationalAddress3.Text;
                    if ((_address.City ?? string.Empty).Trim() != txtCity.Text.Trim())
                        _address.City = txtCity.Text;
                    if ((_address.PostalCode ?? string.Empty).Trim() != txtZip.Text.Trim())
                        _address.PostalCode = txtZip.Text;
                    if ((_address.State ?? string.Empty).Trim() != ddState.SelectedValue)
                        _address.State = ddState.SelectedValue;
                    if (ddCountry.SelectedValue != string.Empty)
                        _address.Country = _context.codeCountry.Find(new object[] { int.Parse(ddCountry.SelectedValue) });
                }
            }
        }

        private void SetEnabled()
        {
            // Determine if this tab is enabled.
            _enabled = true;
            Control ctl = this;
            while (ctl != null)
            {
                if (ctl is WebControl)
                    if (!((WebControl)ctl).Enabled)
                        _enabled = false;
                ctl = ctl.Parent;
            }

            // if the ship-to is the same as the customer address then disable the vaidators
            if (chkSameAsBilling.Checked)
                _enabled = false;

            foreach (Control ctrl in Controls)
                RecurseSetEnabled(ctrl);
            divShipTo.Disabled = !_enabled;

            bool USAddress = (ddCountry.SelectedValue == "1" || ddCountry.SelectedValue == "40");

            if (USAddress)
            {
                RequiredCity.Enabled = _enabled;
                RequiredZip.Enabled = _enabled;
                //RequiredIntlAddress2.Enabled = false;
            }
            else
            {
                RequiredCity.Enabled = false;
                RequiredZip.Enabled = false;
                //RequiredIntlAddress2.Enabled = _enabled;
            }
        }

        private void RecurseSetEnabled(Control ctrl)
        {
            {
                if (ctrl is System.Web.UI.HtmlControls.HtmlGenericControl)
                    foreach (Control ctrl2 in ctrl.Controls)
                        RecurseSetEnabled(ctrl2);
                if (ctrl is BaseValidator)
                    // Since we are using highlighting to show errors in small mode, we can't use client scripting.
                    ((BaseValidator)ctrl).Enabled = _enabled;
            }
        }

        public new void Load(SalesManagerEntities context, tblOrderHeader orderHeader, bool forceUpdate)
        {
            _context = context;
            _orderHeader = orderHeader;
            _address = _orderHeader.ShipTo_Address;
            _person = _orderHeader.ShipTo_Person;

            if (!IsPostBack || forceUpdate)
            {
                // Populate the State drop down.
                if (ddState.Items.Count == 0)
                    foreach (codeState l in from c in context.codeState.Local orderby c.Name select c)
                        ddState.Items.Add(new ListItem(l.Name, l.Abbrev));
                // Populate the country drop down.
                if (ddCountry.Items.Count == 0)
                    foreach (codeCountry l in from c in context.codeCountry.Local orderby c.Name select c)
                        ddCountry.Items.Add(new ListItem(l.Name, l.CountryID.ToString()));

                if (_orderHeader.ShipTo_Address == _orderHeader.Customer.Person.Address)
                    chkSameAsBilling.Checked = true;

                txtName.Text = _person.Name;
                txtFirstName.Text = _person.FirstName;
                txtLastName.Text = _person.LastName;
                txtCompanyName.Text = _orderHeader.ShipTo_CompanyName;
                txtAddress1.Text = _address.Address1;
                txtAddress2.Text = _address.Address2;
                txtInternationalAddress2.Text = _address.Address2;
                txtInternationalAddress3.Text = _address.Address3;
                txtCity.Text = _address.City;
                txtZip.Text = _address.PostalCode;
                if (_address.State != null)
                    ddState.SelectedValue = _address.State;
                ddCountry.SelectedValue = _address.Country.CountryID.ToString();
            }
        }

        protected void chkSameAsBilling_CheckedChanged(object sender, EventArgs e)
        {
            if (chkSameAsBilling.Checked)
            {
                _orderHeader.ShipTo_Address = _orderHeader.Customer.Person.Address;
                _orderHeader.ShipTo_Person = _orderHeader.Customer.Person;
            }
            else
            {
                _orderHeader.ShipTo_Address = new tblAddress();
                _orderHeader.ShipTo_Person = new tblPerson();
                Load(_context, _orderHeader, true);
            }
            SetEnabled();
        }

        //public new void Load()
        //{
            //DataRow drCustomer = site.GetCustomerRecord(Page);

            //txtFirstName.Text = drCustomer["FirstName"].ToString();
            //if (txtFirstName.Text == string.Empty && Page.Request["customer.firstName"] != null)
            //    txtFirstName.Text = Page.Request["customer.firstName"];
            //txtLastName.Text = drCustomer["LastName"].ToString();
            //if (txtLastName.Text == string.Empty && Page.Request["customer.lastName"] != null)
            //    txtLastName.Text = Page.Request["customer.lastName"];
            //txtAddress1.Text = drCustomer["Address1"].ToString();
            //if (txtAddress1.Text == string.Empty && Page.Request["customer.address1"] != null)
            //    txtAddress1.Text = Page.Request["customer.address1"];
            //txtAddress2.Text = drCustomer["Address2"].ToString();
            //if (txtAddress2.Text == string.Empty && Page.Request["customer.address2"] != null)
            //    txtAddress2.Text = Page.Request["customer.address2"];
            //txtCity.Text = drCustomer["City"].ToString();
            //if (txtCity.Text == string.Empty && Page.Request["customer.city"] != null)
            //    txtCity.Text = Page.Request["customer.city"];
            //ddState.SelectedValue = drCustomer["State"].ToString();
            //if (drCustomer["State"].ToString() == string.Empty && Page.Request["customer.state"] != null)
            //    ddState.SelectedValue = Page.Request["customer.state"];
            //txtZip.Text = drCustomer["ZIP"].ToString();
            //if (txtZip.Text == string.Empty && Page.Request["customer.zip"] != null)
            //    txtZip.Text = Page.Request["customer.zip"];
            //txtInternationalAddress2.Text = drCustomer["Address2"].ToString();
            //if (txtInternationalAddress2.Text == string.Empty && Page.Request["customer.address2"] != null)
            //    txtInternationalAddress2.Text = Page.Request["customer.address2"];
            //txtInternationalAddress3.Text = drCustomer["Address3"].ToString();
            //txtCountry.Text = drCustomer["Country"].ToString();

            //txtEmail.Text = drCustomer["EMail"].ToString();
            //if (txtEmail.Text == string.Empty && Page.Request["customer.email"] != null)
            //    txtEmail.Text = Page.Request["customer.email"];
            //txtPhone.Text = drCustomer["Phone"].ToString();
            //if (txtPhone.Text == string.Empty && Page.Request["customer.phone"] != null)
            //    txtPhone.Text = Page.Request["customer.phone"];
        //}

        public void UpdateCustomer()
        {
            //DataRow drCustomer = site.GetCustomerRecord(Page);
            //DataRow drOrder = site.GetFirstOrderData();

            //bool USAddress = chkUsAddress.Checked;

            //// If the order has already been created then populate the order with the shipping information.
            //// If the order has not been created yet, then populate the customer record with the 
            //// shipping info and we will copy that to the new order when it gets created.
            //if (drOrder == null)
            //{
            //    drCustomer["FirstName"] = txtFirstName.Text;
            //    drCustomer["LastName"] = txtLastName.Text;
            //    drCustomer["Address1"] = txtAddress1.Text;
            //    if (USAddress)
            //    {
            //        drCustomer["Address2"] = txtAddress2.Text;
            //        drCustomer["City"] = txtCity.Text;
            //        drCustomer["State"] = ddState.SelectedValue;
            //        drCustomer["ZIP"] = txtZip.Text;
            //        if (Array.Find<String>(canadianStates, delegate(String s) { return s == drCustomer["State"].ToString(); }) != null)
            //            drCustomer["Country"] = "Canada";
            //        else
            //            drCustomer["Country"] = "USA";
            //    }
            //    else
            //    {
            //        drCustomer["Address2"] = txtInternationalAddress2.Text;
            //        drCustomer["Address3"] = txtInternationalAddress3.Text;
            //        drCustomer["Country"] = txtCountry.Text;
            //    }
            //}
            //else
            //{
            //    drOrder["FirstName"] = txtFirstName.Text;
            //    drOrder["LastName"] = txtLastName.Text;
            //    drOrder["Address1"] = txtAddress1.Text;
            //    if (USAddress)
            //    {
            //        drOrder["Address2"] = txtAddress2.Text;
            //        drOrder["City"] = txtCity.Text;
            //        drOrder["State"] = ddState.SelectedValue;
            //        drOrder["ZIP"] = txtZip.Text;
            //        if (Array.Find<String>(canadianStates, delegate(String s) { return s == drCustomer["State"].ToString(); }) != null)
            //            drOrder["Country"] = "Canada";
            //        else
            //            drOrder["Country"] = "USA";
            //    }
            //    else
            //    {
            //        drOrder["Address2"] = txtInternationalAddress2.Text;
            //        drOrder["Address3"] = txtInternationalAddress3.Text;
            //        drOrder["Country"] = txtCountry.Text;
            //    }
            //}

            //string email = txtEmail.Text;
            //drCustomer["EMail"] = email.Substring(0, Math.Min(70, email.Length));
            //string phone = txtPhone.Text.Replace("-", "");
            //drCustomer["Phone"] = phone.Substring(0, Math.Min(20, phone.Length));

            //site.UpdateCustomer(drCustomer);
        }

        //public void Validate()
        //{
        //    bool USAddress = (ddCountry.SelectedValue == "1" || ddCountry.SelectedValue == "40");

        //    //if (USAddress)
        //    //{
        //    //    RequiredCity.Enabled = true;
        //    //    RequiredZip.Enabled = true;
        //    //    RequiredIntlAddress2.Enabled = false;
        //    //}
        //    //else
        //    //{
        //    //    RequiredCity.Enabled = false;
        //    //    RequiredZip.Enabled = false;
        //    //    RequiredIntlAddress2.Enabled = true;
        //    //}

        //    this.Page.Validate();
        //    foreach (Control ctrl in Controls)
        //        if (ctrl is BaseValidator && ((BaseValidator)ctrl).Enabled)
        //        {
        //            Control ctrl2 = FindControl(((BaseValidator)ctrl).ControlToValidate);
        //            if (ctrl2 is LabeledText)
        //                ((LabeledText)ctrl2).Error = !(((BaseValidator)ctrl).IsValid);
        //            else if (ctrl2 is WebControl)
        //                ((WebControl)ctrl2).CssClass = (((BaseValidator)ctrl).IsValid) ? "" : "invalid";
        //        }
        //}
    }
}